<!--
 * @Description: 商家会员档案
-->
<template>
  <div>
    <el-form :inline="true" :model="formInline" class="demo-form-inline" @keyup.enter.native="search()">
      <el-form-item label="店长姓名">
        <br /><br />
        <el-input v-model="formInline.storeManagerName" clearable style="margin-left: -80px; width: 200px"></el-input>
      </el-form-item>

      <el-form-item label="手机号">
        <br /><br />
        <el-input v-model="formInline.phone" clearable style="margin-left: -55px; width: 200px"></el-input>
      </el-form-item>

      <el-form-item label="店铺名称">
        <br /><br />
        <el-input v-model="formInline.storeName" clearable style="margin-left: -70px; width: 200px"></el-input>
      </el-form-item>
      <el-form-item label="店铺状态">
        <br /><br />
        <el-select v-model="formInline.openStatus" clearable style="margin-left: -70px; width: 200px">
          <el-option label="正常营业" :value="1"></el-option>
          <el-option label="已闭店" :value="0"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="所属大区名称">
        <br /><br />
        <el-input v-model="formInline.upOrgZone" style="margin-left: -100px; width: 200px" clearable></el-input>
        <!-- <el-select v-model="formInline.zqName" clearable filterable @change="selCore(formInline.zqName)"
          style="margin-left: -80px; width: 200px">
          <el-option v-for="item in corpList" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select> -->
      </el-form-item>

      <el-form-item label="所属营销区域">
        <br /><br />
        <el-input v-model="formInline.baseName" style="margin-left: -100px; width: 200px" clearable></el-input>
        <!-- <el-select v-model="formInline.jdName" clearable filterable @change="selbase(formInline.jdName)"
          style="margin-left: -80px; width: 200px">
          <el-option v-for="item in RentalPayWay" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select> -->
      </el-form-item>

      <el-form-item label="订单客户编号">
        <br /><br />
        <el-input v-model="formInline.orderCustomerCode" style="margin-left: -100px; width: 200px"
          placeholder="请输入订单客户编号" />
      </el-form-item>

      <el-form-item label="兑换状态">
        <br /><br />
        <el-select v-model="formInline.exchangeSwitch" clearable style="margin-left: -80px; width: 200px">
          <el-option label="全部" value=""></el-option>
          <el-option label="已开启" :value="1"></el-option>
          <el-option label="已关闭" :value="0"></el-option>
        </el-select>
        <!-- <el-date-picker v-model="formInline.dateRange" type="daterange" align="right" unlink-panels range-separator="至"
          style="margin-left: -80px; width: 410px" start-placeholder="上岗开始日期" end-placeholder="上岗结束日期"
          value-format="yyyy-MM-dd"></el-date-picker> -->
      </el-form-item>

      <el-form-item style="margin-top:45px;text-align:right;">
        <el-button type="primary" @click="search()" size="mini" icon="el-icon-search">查询</el-button>
        <el-button type="primary" @click="kong()" size="mini" icon="el-icon-delete">清空</el-button>
        <el-button type="success" plain @click="exportExcel()" size="mini" icon="el-icon-s-data"
          :loading="outLoading">导出</el-button>
        <el-button :loading="exportLoading" type="success" @click="exportFile()" size="mini"
          icon="el-icon-download">下载导出模板</el-button>
        <UploadFilesBtn style="display: inline-block;margin: 0 10px;"
          url="/api//member-service/v1/memberBonuspoint/bonusAddExcelImportCheck" @change="uploadChange">
          <template slot-scope="scope">
            <el-button type="warning" size="mini" icon="el-icon-upload2" :loading="scope.loading">表格导入赠送</el-button>
          </template>
        </UploadFilesBtn>
        <el-button type="danger" @click="$router.push({ name: 'batchSendMerchantMember' })" plain size="mini"
          icon="el-icon-folder-checked">批量赠送</el-button>
      </el-form-item>
    </el-form>

    <div class="table-wrapper">
      <el-table :data="tableData" style="width: 100%" border height="480px"
        :header-cell-style="{ background: '#eef1f6', color: '#606266' }" v-loading="loading">
        <el-table-column type="index" label="序号" align="center" width="60"></el-table-column>
        <el-table-column prop="storeName" label="店铺名称" align="center" :min-width="200"></el-table-column>
        <el-table-column prop="authCode" label="店铺授权码" align="center" :min-width="200"></el-table-column>
        <el-table-column prop="orderCustomerCode" label="订单客户编号" align="center" :min-width="200"></el-table-column>
        <el-table-column prop="upOrgZone" label="所属大区" align="center" :min-width="200"></el-table-column>
        <el-table-column prop="baseName" label="所属营销区域" align="center" :min-width="200"></el-table-column>
        <el-table-column prop="merchantDirectedIntegral" label="可用定向云币" align="center"
          :min-width="200"></el-table-column>
        <el-table-column label="兑换状态" align="center">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.exchangeSwitch" active-color="#13ce66" :active-value="1" :inactive-value="0"
            @change="updateStatus(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="merchantIntegral" label="可用普通云币" align="center" :min-width="200"></el-table-column>
        <el-table-column prop="storeManagerName" label="店长姓名" align="center" :min-width="200"></el-table-column>
        <el-table-column prop="legalPersonPhone" label="手机号" align="center" :min-width="200"></el-table-column>
        <el-table-column label="状态" align="center">
          <template slot-scope="scope">
            {{ scope.row.openStatus === 0 ? '已闭店' : '正常营业' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button v-if="isLzqUser" type="text" size="mini" @click="relatedOrder(scope.row)">关联订单</el-button>
            <el-button v-if="scope.row.merchantDirectedIntegral < 0" type="text" size="mini"
              @click="recallOrder(scope.row)">撤回订单</el-button>
            <el-button type="text" size="mini" @click="relatedCoin(scope.row)">云币明细</el-button>
            <el-button v-if="scope.row.openStatus == 1" type="text" size="mini"
              @click="giveCoin(scope.row)">赠送云币</el-button>
            <el-button type="text" size="mini" @click="syncStoreCoin(scope.row)">同步商家云币</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="block" style="margin-top: 10px">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :page-sizes="[10, 20, 30, 50, 100, 500]" :current-page="listQuery.current" :page-size="listQuery.size"
        layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
    </div>

    <!-- 赠送酒币 -->
    <GiveCoinDialog :show.sync="showGiveCoinDialog" :memberId="curMemberId" :type="1" :orgSeq="curOrgSeq"
      @refresh="search" />

    <!-- 批量赠送酒币结果 -->
    <BatchCoinResultDialog ref="batchCoinResultRef" :show.sync="showBatchCoinDialog" :detail="batchDetail"
      @refresh="search">
      <template slot="batch-upload">
        <UploadFilesBtn style="display: inline-block;margin: 0 10px;"
          url="/api//member-service/v1/memberBonuspoint/bonusAddExcelImportCheck" @change="uploadChange">
          <template slot-scope="scope">
            <el-button type="warning" :loading="scope.loading">重新上传</el-button>
          </template>
        </UploadFilesBtn>
      </template>
    </BatchCoinResultDialog>

    <!-- 撤回订单弹框 -->
    <RecallOrderDialog :show.sync="showRecallDialog" :authCode="recallAuthCode" :orgSeq="recallOrgSeq"
      @refresh="getList" />
  </div>
</template>

<script>
import {
  refreshMerchantIntegral,
  getStoreExcelBonusAddTemplate
} from '@/api/goodsExchange';
import { queryStoreUserInfoExport, exchangeRightSwitch } from '@/api/shopMemberset';
import { qryStore } from '@/api/addShopapply';
import { getStoreExcel } from '@/api/download';
import { getAllZone, getAllBase } from '@/api/addShopapply.js';
import GiveCoinDialog from './components/GiveCoinDialog.vue';
import UploadFilesBtn from '@/components/UploadFilesBtn.vue';
import BatchCoinResultDialog from './components/BatchCoinResultDialog.vue';
import RecallOrderDialog from './components/RecallOrderDialog.vue';
export default {
  components: {
    GiveCoinDialog,
    UploadFilesBtn,
    BatchCoinResultDialog,
    RecallOrderDialog,
  },
  data() {
    return {
      // memberId: '',
      formInline: {
        storeManagerName: '',
        phone: '',
        storeName: '',
        openStatus: '',
        upOrgZone: '',
        baseName: '',
        dateRange: [],
        orderCustomerCode: '',
        exchangeSwitch: ''
      },
      loading: false,
      total: 0,
      tableData: [],
      listQuery: {
        current: 1,
        size: 10,
      },
      orgSeq: '', // 门店组织机构编码
      logininfo: null, // 登录信息

      corpList: [], // 大区列表
      RentalPayWay: [], //营销区域列表

      // 赠送酒币相关
      showGiveCoinDialog: false,
      curMemberId: '',
      curOrgSeq: '',
      exportLoading: false,

      // 批量导入酒币
      showBatchCoinDialog: false,
      batchDetail: null,

      // 撤回
      showRecallDialog: false,
      recallAuthCode: null,
      recallOrgSeq: null,

      // 是否是内部使用账号
      isLzqUser: false,

      // 导出数据
      outLoading: false
    };
  },
  created() {
    this.logininfo = localStorage.getItem('logininfo');
    this.orgSeq = JSON.parse(this.logininfo).orgSeq;
    this.selCore(this.orgSeq);
    this._getAllZone();
    this.search();

    const userName = this.logininfo.userName ? this.logininfo.userName : '';
    const userType = this.logininfo.userType ? this.logininfo.userType : '';
    if (
      this.$route.query.username == 'lzq' ||
      (userName == 'lzq' && userType == '1')
    ) {
      this.isLzqUser = true;
    }
  },

  methods: {
    search() {
      this.listQuery.current = 1;
      this.getList();
    },
    handleSizeChange(val) {
      this.listQuery.size = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.current = val;
      this.getList();
    },
    getList() {
      this.loading = true;
      const data = {
        size: this.listQuery.size,
        current: this.listQuery.current,
        condition: {
          ...this.formInline,
          onboardDateStart:
            this.formInline.dateRange !== null &&
              this.formInline.dateRange.length > 0
              ? this.formInline.dateRange[0]
              : '',
          onboardDateEnd:
            this.formInline.dateRange !== null &&
              this.formInline.dateRange.length > 1
              ? this.formInline.dateRange[1]
              : '',
          orgSeq: this.orgSeq,
          userType: 5,
        },
      };
      qryStore(data)
        .then((res) => {
          this.total = res.total;
          this.tableData = res.records;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    selCore(value) {
      if (value != '' && value != undefined && value != null) {
        this.orgSeq = value;
        let data = {
          code: value,
        };
        getAllBase(data).then((res) => {
          this.RentalPayWay = res.result;
          this.formInline.jdName = '';
        });
      } else if (this.formInline.jdName != '') {
        this.orgSeq = this.formInline.jdName;
      } else {
        this.orgSeq = JSON.parse(this.logininfo).orgSeq;
      }
    },
    selbase(value) {
      if (value != '' && value != undefined && value != null) {
        this.orgSeq = value;
      } else if (this.formInline.zqName != '') {
        this.orgSeq = this.formInline.zqName;
      } else {
        this.orgSeq = JSON.parse(this.logininfo).orgSeq;
      }
    },

    _getAllZone() {
      let data = {};
      getAllZone(data).then((res) => {
        this.corpList = res.result;
      });
    },

    kong() {
      this.formInline = this.$options.data().formInline;
      this.orgSeq = JSON.parse(this.logininfo).orgSeq;
    },

    // 赠送云币
    giveCoin(curInfo) {
      // this.curMemberId = curInfo.userId;
      this.curMemberId = curInfo.orgSeq;
      this.curOrgSeq = curInfo.orgSeq;
      if (!curInfo.orgSeq) {
        this.$message.error('该用户未设置营销区域');
        return;
      }
      this.showGiveCoinDialog = true;
    },

    // 云币明细
    relatedCoin(curInfo) {
      this.$router.push({
        name: 'cloudCoinDetail',
        params: {
          memberId: curInfo.orgSeq,
          type: 1,
        },
      });
    },

    // 关联的订单查询
    relatedOrder(curInfo) {
      if (!curInfo.authCode) {
        this.$message.error('该用户未设置店铺授权码');
      }
      // return
      this.$router.push({
        name: 'normalOrderSearch',
        params: {
          authCode: curInfo.authCode,
        },
      });
    },

    // 模板文件
    exportFile() {
      this.exportLoading = true;
      const data = {
        size: this.listQuery.size,
        current: this.listQuery.current,
        condition: {
          ...this.formInline,
          onboardDateStart:
            this.formInline.dateRange !== null &&
              this.formInline.dateRange.length > 0
              ? this.formInline.dateRange[0]
              : '',
          onboardDateEnd:
            this.formInline.dateRange !== null &&
              this.formInline.dateRange.length > 1
              ? this.formInline.dateRange[1]
              : '',
          orgSeq: this.orgSeq,
          userType: 5,
        },
      };
      getStoreExcelBonusAddTemplate(data)
        .then((res) => {
          const link = document.createElement('a');
          let blob = new Blob([res], {
            type: 'application/vnd.ms-excel',
          });
          link.style.display = 'none';
          //设置连接
          link.href = URL.createObjectURL(blob);
          link.download = '模板文件.xlsx';
          document.body.appendChild(link);
          //模拟点击事件
          link.click();
        })
        .finally(() => {
          this.exportLoading = false;
        });
    },

    uploadChange(response) {
      this.batchDetail = {};
      this.batchDetail = response.result;

      if (!this.showBatchCoinDialog) {
        this.showBatchCoinDialog = true;
      } else {
        this.showBatchCoinDialog = false;
        setTimeout(() => {
          this.showBatchCoinDialog = true;
        }, 300);
      }
    },

    syncStoreCoin(curInfo) {
      refreshMerchantIntegral({ orgSeq: curInfo.orgSeq }).then((res) => {
        if (res.code == 1) {
          this.$message.success(res.message || '同步成功');
          this.getList();
        } else {
          this.$message.error(res.message || '同步失败');
        }
      });
    },

    // 撤回订单
    recallOrder(curItem) {
      this.recallAuthCode = curItem.authCode;
      this.recallOrgSeq = curItem.orgSeq;
      this.showRecallDialog = true;
    },

    exportExcel() {
      this.outLoading = true;
      const data = {
        size: this.listQuery.size,
        current: this.listQuery.current,
        condition: {
          ...this.formInline,
          onboardDateStart:
            this.formInline.dateRange !== null &&
              this.formInline.dateRange.length > 0
              ? this.formInline.dateRange[0]
              : '',
          onboardDateEnd:
            this.formInline.dateRange !== null &&
              this.formInline.dateRange.length > 1
              ? this.formInline.dateRange[1]
              : '',
          orgSeq: this.orgSeq,
          userType: 5,
        },
      };
      queryStoreUserInfoExport(data)
        .then((res) => {
          const byteCharacters = atob(res); //将base64转换为二进制字符串
          const byteNumbers = new Array(byteCharacters.length);
          for (let i = 0; i < byteCharacters.length; i++) {
            byteNumbers[i] = byteCharacters.charCodeAt(i);
          }
          const byteArray = new Uint8Array(byteNumbers);

          const link = document.createElement('a');
          let blob = new Blob([byteArray], {
            type: 'application/vnd.ms-excel',
          });
          link.style.display = 'none';
          //设置连接
          link.href = URL.createObjectURL(blob);
          link.download = '商家会员列表.xlsx';
          document.body.appendChild(link);
          //模拟点击事件
          link.click();
        })
        .finally(() => {
          this.outLoading = false;
        });
    },

    updateStatus(row) {
      row.exchangeSwitch = row.exchangeSwitch == 1 ? 0 : 1;
      this.$confirm(`是否${row.exchangeSwitch == 1 ? '关闭' : '开启'}状态?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        exchangeRightSwitch({
          authCode: row.authCode,
          exchangeSwitch: row.exchangeSwitch == 1 ? 0 : 1,
        }).then((res) => {
          if (res.code == 1) {
            this.$message({
              message: '操作成功',
              type: 'success',
            });
            this.search();
          } else {
            this.$message.error(res.message || '操作失败');
          }
        })
      })
    }
  },
};
</script>

<style lang="less" scoped>
.el-form-item .el-select {
  width: 100%;
}
</style>
<style lang="scss" scoped>
.demo-form-inline {
  /deep/ .el-form-item__content {
    line-height: normal;
  }
}

.table-wrapper {
  /deep/ .el-table__fixed-right .el-table__fixed-body-wrapper {
    height: 420px !important;
  }
}
</style>
